package com.yipin.neimeng.service.impl;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yipin.neimeng.constant.ErrorConstant;
import com.yipin.neimeng.dbpojo.NeimengCmccOrders;
import com.yipin.neimeng.mapper.NeimengCmccOrdersMapper;
import com.yipin.neimeng.request.YunShuOrderRequest;
import com.yipin.neimeng.service.NeimengCmccOrdersService;
import com.yipin.neimeng.util.HttpJsonInvokeDemo;
import com.yipin.neimeng.util.Md5Util;
import com.yipin.neimeng.vo.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class NeimengCmccOrdersServiceImpl extends ServiceImpl<NeimengCmccOrdersMapper, NeimengCmccOrders> implements NeimengCmccOrdersService {
    private static final String OWNKEY = "0duyxk7rocwabeoo9fbpgujk659cubo8";


    private static final String METHOD_URL = "CRM_CS_SRVUPD_SMS_CHECK_001";   //接口编码

    private static final String AppId = "502739";   //应用AppId

    private static final String Url = "http://111.56.125.2:18500";

    private static final String APP_KEY = "b49644385f34023eb9ab929fcbe79bb3";

    @Override
    public ResultMsg<?> sendorder(YunShuOrderRequest yunShuOrderRequest) {
        String phone = yunShuOrderRequest.getPhone();
        String code = yunShuOrderRequest.getSmsCode();
        String ownSign = yunShuOrderRequest.getOwnsign();
        String trraceLogId = yunShuOrderRequest.getTraceLogId();
        String ip = yunShuOrderRequest.getIp();
        String channelCode = yunShuOrderRequest.getChannelCode();
        String productCode = yunShuOrderRequest.getProductCode();
        String productName = yunShuOrderRequest.getProductName();
        String union = yunShuOrderRequest.getUnion();
        String pages = yunShuOrderRequest.getPage();
        String thirdContact = yunShuOrderRequest.getThirdContact();
        String unionCode = yunShuOrderRequest.getUnionCode();
        String unionAtg = yunShuOrderRequest.getUnionAtg();
        String unionName = yunShuOrderRequest.getUnionName();
        String flowIds = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String timestamps = yunShuOrderRequest.getTimestamp();
        String result;
        String  msg;
        String secContact =yunShuOrderRequest.getSecContact();

        // 校验签名是否正确
//        if (!ownSign.equalsIgnoreCase(Md5Util.encryptMD5(timestamps + OWNKEY))) {
//            return ResultMsg.fail(ErrorConstant.paramsErrorCode, ErrorConstant.signErrorMsg, null);
//        }

        NeimengCmccOrders neimengCmccOrders = new NeimengCmccOrders();

        try{
            String method = METHOD_URL;   // 接口编码
            String appId = AppId;   // 应用AppId
            String appkey = APP_KEY;
            String opCode = "SYS71015406";
            String opOrgId = "71012628";
            String channelId = "9137";
            JSONObject reqJson = new JSONObject();
            JSONObject pubJson = new JSONObject();
            JSONObject pageJson = new JSONObject();

            String orderNumber = generateRandomOrderNumber(12);
            neimengCmccOrders.setOrderNumber(orderNumber);
            neimengCmccOrders.setThirdContact(thirdContact);
            neimengCmccOrders.setSecContact(secContact);
            neimengCmccOrders.setIp(ip);

            pubJson.put("OP_CODE", "SYS71015406");
            pubJson.put("REQ_SERIAL_NO", orderNumber);
            pubJson.put("CHANNEL_ID", "9137");
            pubJson.put("OP_ORG_ID", "71012628");

            pageJson.put("PAGE_SIZE", "2");
            pageJson.put("CURRENT_PAGE", "1");

            reqJson.put("PUB_INFO", pubJson);
            reqJson.put("PAGE_INFO", pageJson);

            // 业务参数,Json格式
            JSONObject busiJson = new JSONObject();
            busiJson.put("ACCESS_NUM", phone);
            busiJson.put("VERIFY_NUM", code);
            busiJson.put("BUSI_CODE", "0001");


            reqJson.put("BUSI_INFO", busiJson);

            JSONObject inputJson = new JSONObject();
            inputJson.put("REQ_PARAM", reqJson);

            String busiParam = inputJson.toString();


            String headerString="http://111.56.125.2:21017/oppf?method="+method+
                    "&appId="+appId+
                    "&OP_CODE="+opCode+
                    "&OP_ORG_ID="+opOrgId+
                    "&CHANNEL_ID="+channelId+
                    "&timestamp="+new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar
                    .getInstance().getTime());

            log.info("请求地址："+headerString);

            String find = HttpJsonInvokeDemo.encryptMessage(busiParam,"1",APP_KEY,"AES");

            log.info("加密后的参数："+find);
            neimengCmccOrders.setRequestText(busiParam);
            JSONObject yunShuRequest = new JSONObject();
            yunShuRequest.put("yunShurequest",yunShuOrderRequest);
            neimengCmccOrders.setYunShurequest(yunShuRequest.toString());
            this.updateById(neimengCmccOrders);
            log.info("验证码校验请求参数:{}",busiParam);
            try(HttpResponse response = HttpUtil.createPost(headerString)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(find)
                    .execute()){
                result = response.body();
            }catch (Exception e) {
                throw new RuntimeException("HTTP 请求失败", e);
            }

            HttpJsonInvokeDemo demo = new HttpJsonInvokeDemo();
            String aes = HttpJsonInvokeDemo.decryptMessage(result, "1", APP_KEY,"AES");

            log.info("校验验证码解密后的响应结果："+aes);
            if (StringUtils.isBlank(aes)) {
                return ResultMsg.fail(ErrorConstant.paramsErrorCode, ErrorConstant.cmccErrorMsg, null);
            }
            neimengCmccOrders.setResponseText(aes);
            this.updateById(neimengCmccOrders);

            JSONObject resultJsonObject = JSONObject.parseObject(aes);
            // 获取RSP_PARAM对象
            JSONObject rspParam = resultJsonObject.getJSONObject("RSP_PARAM");

            // 获取PUB_INFO对象
            JSONObject pubInfo = rspParam.getJSONObject("PUB_INFO");

            // 获取CODE值
            String codes = pubInfo.getString("CODE");

            if ("0".equals(codes)) {
                method = "CRM_SO_GENACC_OFFER_OFFACC_001";
                appId = AppId;   //应用AppId
                appkey= APP_KEY;
                opCode = "SYS71015406";
                opOrgId= "71012628";
                channelId= "9137";

                String headerStrings="http://111.56.125.2:21017/oppf?method="+method+
                        "&appId="+appId+
                        "&OP_CODE="+opCode+
                        "&OP_ORG_ID="+opOrgId+
                        "&CHANNEL_ID="+channelId+
                        "&timestamp="+new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar
                        .getInstance().getTime());

                log.info("请求地址："+headerStrings);


                // 创建最外层的JSONObject
                JSONObject reqParam = new JSONObject();

                // 创建BUSI_INFO对象
                JSONObject busiInfo = new JSONObject();
                busiInfo.put("ACCESS_NUM", phone);

                // 创建OFFER_LIST数组
                JSONArray offerList = new JSONArray();

                // 创建OFFER_INFO对象
                JSONObject offerInfo = new JSONObject();
                offerInfo.put("OFFER_ID", productCode);
                offerInfo.put("OPER_CODE", "1");

                // 将OFFER_INFO添加到OFFER_LIST数组
                JSONObject offerListElement = new JSONObject();
                offerListElement.put("OFFER_INFO", offerInfo);
                offerList.add(offerListElement);

                // 将OFFER_LIST添加到BUSI_INFO
                busiInfo.put("OFFER_LIST", offerList);

                // 创建PUB_INFO对象
                JSONObject pubInfos = new JSONObject();
                pubInfos.put("OP_CODE", "SYS71015406");
                pubInfos.put("REQ_SERIAL_NO", orderNumber);
                pubInfos.put("CHANNEL_ID", "9137");
                pubInfos.put("OP_ORG_ID", "71012628");

                // 将BUSI_INFO和PUB_INFO添加到REQ_PARAM
                reqParam.put("BUSI_INFO", busiInfo);
                reqParam.put("PUB_INFO", pubInfos);

                // 创建最外层的REQ_PARAM对象
                JSONObject outerObject = new JSONObject();
                outerObject.put("REQ_PARAM", reqParam);


                boolean orderSave = getXinjiangSaveOrder(neimengCmccOrders, yunShuOrderRequest);
                if (!orderSave) {
                    return ResultMsg.fail(ErrorConstant.paramsErrorCode, ErrorConstant.orderErrorMsg, null);
                }

                neimengCmccOrders.setRequestText(outerObject.toString());
                log.info("个人业务办理入参："+outerObject);

                String finds = HttpJsonInvokeDemo.encryptMessage(outerObject.toString(),"1",APP_KEY,"AES");

                log.info("加密后的参数："+finds);

                try(HttpResponse response = HttpUtil.createPost(headerStrings)
                        .header(Header.CONTENT_TYPE, "application/json")
                        .body(finds)
                        .execute()){
                    result = response.body();
                }catch (Exception e) {
                    throw new RuntimeException("HTTP 请求失败", e);
                }
                String reus = HttpJsonInvokeDemo.decryptMessage(result, "1", APP_KEY,"AES");

                log.info("解密后的响应结果："+reus);
                neimengCmccOrders.setResponseText(reus);

                neimengCmccOrders.setUpdateDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                JSONObject jsonObject1 = JSON.parseObject(reus);
                String orderCode = jsonObject1.getJSONObject("RSP_PARAM").getJSONObject("PUB_INFO").getString("CODE");

                log.info("code:"+orderCode);
                this.updateById(neimengCmccOrders);
                if ("0".equals(orderCode)) {
                    neimengCmccOrders.setStatus("2");

                    String resultCode = jsonObject1.getJSONObject("RSP_PARAM")
                            .getJSONObject("BUSI_INFO")
                            .getString("resultCode");
                    log.info("ORDER_ID" + resultCode);
                    String reqSerialNo = jsonObject1.getJSONObject("RSP_PARAM")
                            .getJSONObject("PUB_INFO")
                            .getString("REQ_SERIAL_NO");
                    String busiSerialNo = jsonObject1.getJSONObject("RSP_PARAM")
                            .getJSONObject("PUB_INFO")
                            .getString("BUSI_SERIAL_NO");


                    neimengCmccOrders.setOrderId(resultCode);
                    neimengCmccOrders.setOperatorOrderNo(reqSerialNo);

                    neimengCmccOrders.setTranseq(busiSerialNo);

                    JSONObject datas = new JSONObject();
                    datas.put("OrderNo", neimengCmccOrders.getOrderNo());
                    datas.put("OperatorOrderNo", reqSerialNo);
                    this.updateById(neimengCmccOrders);
                    return ResultMsg.success(ErrorConstant.paramsSuccessCode,"成功", datas);
                }else {
                    JSONObject excet = JSON.parseObject(reus);
                    String message = excet.getJSONObject("RSP_PARAM")
                            .getJSONObject("PUB_INFO")
                            .getString("MESSAGE");
                    neimengCmccOrders.setStatus("0");
                    this.updateById(neimengCmccOrders);
                    return ResultMsg.fail(ErrorConstant.paramsErrorCode, message, jsonObject1);
                }

            }else {
                JSONObject excet = JSON.parseObject(aes);
                String message = excet.getJSONObject("RSP_PARAM")
                        .getJSONObject("PUB_INFO")
                        .getString("MESSAGE");
                neimengCmccOrders.setStatus("0");
                this.updateById(neimengCmccOrders);
                return ResultMsg.fail(ErrorConstant.paramsErrorCode, message, aes);
            }

        } catch (Exception e) {
            log.info("接口异常:{}",e);
            neimengCmccOrders.setException(e.toString());
            this.updateById(neimengCmccOrders);
        }
        return ResultMsg.fail(ErrorConstant.paramsErrorCode, "失败", null);
    }

    @Override
    public ResultMsg<?> selectOrder(YunShuOrderRequest yunShuOrderRequest) {
        String phone = yunShuOrderRequest.getPhone();
        String code = yunShuOrderRequest.getSmsCode();
        String ownSign = yunShuOrderRequest.getOwnsign();
        String trraceLogId = yunShuOrderRequest.getTraceLogId();
        String ip = yunShuOrderRequest.getIp();
        String channelCode = yunShuOrderRequest.getChannelCode();
        String productCode = yunShuOrderRequest.getProductCode();
        String productName = yunShuOrderRequest.getProductName();
        String union = yunShuOrderRequest.getUnion();
        String unionCode = yunShuOrderRequest.getUnionCode();
        String unionAtg = yunShuOrderRequest.getUnionAtg();
        String unionName = yunShuOrderRequest.getUnionName();
        String flowIds = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String timestamps = yunShuOrderRequest.getTimestamp();
        String result;

        try{
           String method = "CRM_SO_INF_PRODORDER_QRY_005";
           String appId = AppId;   //应用AppId
           String appkey= APP_KEY;
           String opCode = "SYS71110784";
           String opOrgId= "71110145";
           String channelId= "2001";
           String url = sendOrder(method,appId,appkey,opCode,opOrgId,channelId);
            log.info("请求地址："+url+"\n\n\n\n\n\n");

            JSONObject orderBody = new JSONObject();
            orderBody.put("SUBBER_ID",""); //用户Id
            orderBody.put("CUST_ID","");  //客户ID
            orderBody.put("ACCESS_NUM",phone);  //接入号码
            orderBody.put("OFFER_INS_ID","");  //商品实例Id
            orderBody.put("QRY_TYPE","");  //查询类型  0:现订购商品  1:历史订购商品  2:全部订购商品
            orderBody.put("VALID_DATE","");  //生效日期
            orderBody.put("OFFER_TYPE_LIST","");  //商品类型列表
            orderBody.put("OFFER_TYPE_INFO","");  //商品类型信息
            orderBody.put("OFFER_TYPE","");  //商品类型
            orderBody.put("OFFER_LIST","");  //商品列表
            orderBody.put("OFFER_INFO","");  //商品信息
            orderBody.put("OFFER_ID","");  //商品ID
            JSONObject selectData = new JSONObject();
            selectData.put("body", orderBody);

//            String offerbodyStr = JSON.toJSONString(selectData);
            log.info("查询订单入参："+orderBody);
            try(HttpResponse response = HttpUtil.createPost(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(orderBody.toJSONString())
                    .execute()){
                result = response.body();
            }catch (Exception e) {
                throw new RuntimeException("HTTP 请求失败", e);
            }
            log.info("查询订单入参响应结果："+result);
            if (StringUtils.isBlank(result)) {
                return ResultMsg.fail(ErrorConstant.paramsErrorCode, ErrorConstant.cmccErrorMsg, null);
            }
            JSONObject findorder = JSONObject.parseObject(result);
            if ("0".equals(findorder.getString("retCode"))) {
                ResultMsg.success(ErrorConstant.paramsSuccessCode,"成功",result);
            }else {
                ResultMsg.fail(ErrorConstant.paramsErrorCode, ErrorConstant.cmccErrorMsg, null);
            }

        }catch (Exception e){
            log.error("查询订单异常",e);
        }

        return ResultMsg.fail(ErrorConstant.paramsErrorCode,"失败", null);
    }

    @Override
    public ResultMsg<?> orderDate(YunShuOrderRequest yunShuOrderRequest) {

        return null;
    }

    public boolean getXinjiangSaveOrder(NeimengCmccOrders neimengCmccOrders,YunShuOrderRequest yunShuOrderRequest) {
        neimengCmccOrders.setOrderNo("NMCM"+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtil.randomString(6));
        neimengCmccOrders.setChannelCode(yunShuOrderRequest.getChannelCode());
        neimengCmccOrders.setPhone(yunShuOrderRequest.getPhone());
        neimengCmccOrders.setProductCode(yunShuOrderRequest.getProductCode());
//        neimengCmccOrders.setSmsCode();
        neimengCmccOrders.setStatus("1");
        neimengCmccOrders.setProductName(yunShuOrderRequest.getProductName());
        neimengCmccOrders.setCreateDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        neimengCmccOrders.setOutoOrderNo(yunShuOrderRequest.getOutoOrderNo());
        neimengCmccOrders.setSelectCont(0);
        return this.save(neimengCmccOrders);
    }

    private String sendOrder(String method,String appId,String appkey,String opCode,String opOrgId,String channelId) {
        return Url +
                "?APP_ID=" + appId +
                "&APP_KEY="+ appkey +
                "&method=" + method +
                "&OP_CODE=" + opCode +
                "&OP_ORG_ID=" + opOrgId +
                "&CHANNEL_ID=" + channelId;
    }

    public static String generateRandomOrderNumber(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int digit = random.nextInt(10); // 生成0-9之间的随机数字
            sb.append(digit);
        }

        return sb.toString();
    }
}
